package advanced.thread;

/**
 * 龟兔赛跑
 * 利用线程实现
 */
public class L_Runnable_Demo {
    public static void main(String[] args) {
        Racer racer = new Racer();
        //抢夺同一份资源
        new Thread(racer, "乌龟").start();
        new Thread(racer, "兔子").start();
    }
}

class Racer implements Runnable {
    private static String winnver;

    @Override
    public void run() {
        for (int steps = 1; steps <= 100; steps++) {
            System.out.println(Thread.currentThread().getName() + "-->" + steps);
            if (Thread.currentThread().getName().equals("兔子") && steps % 20 == 0) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //判断比赛是否结束
            boolean flag = gameOver(steps);
            if (flag) {
                System.out.println("game  over");
                break;
            }
        }
    }

    /**
     * 是否存在胜利者
     *
     * @param steps
     * @return
     */
    private boolean gameOver(int steps) {
        if (winnver != null) return true;//存在胜利着
        else if (steps == 100) {
            winnver = Thread.currentThread().getName();
            System.out.println("winner is " + winnver);
            return true;
        }
        return false;
    }
}